package com.geek.thread.base;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 十个线程对数字进行自增操作
 */
public class LockTest {

	static int total = 0;

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch countDownLatch = new CountDownLatch(1);
		ReentrantLock lock = new ReentrantLock(false);//true为公平锁，false为不公平锁
		for (int i = 0; i < 10; i++) {
			new Thread(){
				@SneakyThrows
				@Override
				public void run() {
					countDownLatch.await();
					for (int j = 0; j <1000; j++) {
						lock.lock();//加独占锁
						//其实这里面是分了三步指令，所以线程执行的时候才会出现最终结果小于10000
						total++;
//						total = total +1;
						lock.unlock();//解锁
					}
				}
			}.start();
		}

		Thread.sleep(1000);
		countDownLatch.countDown();
		Thread.sleep(2000);
		System.out.println("加出来的结果："+total);
	}

}
